import Router from '@koa/router';
import ExportImportController from '@/controllers/ExportImportController';
import { auth } from '@/middlewares';
import { upload } from '@/middlewares/upload';

const router = new Router({
  prefix: '/api/export-import',
});

/**
 * 通用导入导出路由
 */

// 导出数据（前端传入数据和列配置）
router.post(
  '/export',
  auth,
  ExportImportController.export.bind(ExportImportController)
);

// 导入数据（解析Excel返回JSON）
router.post(
  '/import',
  auth,
  async (ctx, next) => {
    await new Promise((resolve, reject) => {
      upload.single('file')(ctx.req as any, ctx.res as any, (err: any) => {
        if (err) reject(err);
        else resolve(undefined);
      });
    });
    await next();
  },
  ExportImportController.import.bind(ExportImportController)
);

// 下载导入模板
router.get(
  '/template',
  auth,
  ExportImportController.downloadTemplate.bind(ExportImportController)
);

export default router;
